# -*- coding: utf-8 -*-
""" 
@author: ertao.xyz
@create: 2021-10-09 12:01
@description: 
"""
import os
import shutil
from pathlib import Path
from fastapi import APIRouter, File, UploadFile, Request, Response
from typing import List, Any, Union
from tempfile import NamedTemporaryFile
from utils.logger import logger
from core.settings import APISettings
from utils.response_code import HttpStatus, ResultResponse

from .common import save_file

router = APIRouter()


@router.post("/files/")
async def create(fileS: List[bytes] = File(...)):
    return {"file_sizes": [len(file) for file in fileS]}


@router.post("/upload/files")
async def upload_file(request: Request, files: List[UploadFile] = File(...)):
    for file in files:
        await save_file(user=request.state.user, path='/assets', file=file)
    return {"filenames": [file.filename for file in files]}


@router.post("/upload/file", summary="上传图片")
async def upload_image(request: Request,
                       file: UploadFile = File(...)
                       ):
    path = await save_file(user=request.state.user, path='/assets', file=file)
    if path:
        return ResultResponse(result=path)
    else:
        return Response(status_code=506)
    # logger.info(f"用户{request.state.user.username}->上传文件:{file.filename}")
    #
    # # 本地存储临时方案，一般生产都是使用第三方云存储OSS(如七牛云, 阿里云)
    # save_dir = f"{APISettings.BASE_PATH}/assets"
    # if not os.path.exists(save_dir):
    #     os.mkdir(save_dir)
    #
    # try:
    #     suffix = Path(file.filename).suffix
    #
    #     with NamedTemporaryFile(delete=False, suffix=suffix, dir=save_dir) as tmp:
    #         shutil.copyfileobj(file.file, tmp)
    #         tmp_file_name = Path(tmp.name).name
    # finally:
    #     file.file.close()

    # return ResultResponse(result={"image": f"http://127.0.0.1:8010/assets/{tmp_file_name}"})
